<template>
  <div>
    <!-- 导航条区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <!-- 添加动态参数的面板 -->
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <!-- 添加静态属性的面板 -->
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="注意：只能为第三级分类设置相关参数"
                type="warning"
                :closable="false"
                show-icon>
      </el-alert>
      <el-row class="rowclass">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader v-model="selectCate"
                       :options="cateList"
                       :props="cateprops"
                       @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName"
               @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数"
                     name="many">
          <el-button type="primary"
                     size="mini"
                     :disabled='isBtndisabled'
                     @click='addDialogVisible=true'>添加动态参数</el-button>
          <el-table :data="manyTableData"
                    border
                    stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close='deleteTag(i,scope.row)'>{{item}}</el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="$event.target.blur"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称"
                             prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           size="mini"
                           @click="editDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger"
                           size="mini"
                           @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性"
                     name="only">
          <el-button type="primary"
                     size="mini"
                     :disabled='isBtndisabled'
                     @click='addDialogVisible=true'>添加静态属性</el-button>
          <el-table :data="onlyTableData"
                    border
                    stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close='deleteTag(i,scope.row)'>{{item}}</el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="$event.target.blur"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称"
                             prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           size="mini"
                           @click="editDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger"
                           size="mini"
                           @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数对话框 -->
      <el-dialog :title="'添加'+Dialogtext"
                 :visible.sync="addDialogVisible"
                 width="50%"
                 @close='addDialogClose'>
        <el-form :model="addForm"
                 :rules="addFormRules"
                 ref="addFormRef"
                 label-width="100px">
          <el-form-item :label="Dialogtext"
                        prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addParmas">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数对话框 -->
      <el-dialog :title="'修改'+Dialogtext"
                 :visible.sync="editDialogVisible"
                 width="50%"
                 @close='editDialogClose'>
        <el-form :model="editForm"
                 :rules="editFormRules"
                 ref="editFormRef"
                 label-width="100px">
          <el-form-item :label="Dialogtext"
                        prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editParmas">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    return {
      cateList: [],
      cateprops: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 被选中的商品
      selectCate: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      editDialogVisible: false,
      editForm: {

      },
      editFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品列表
    getCateList: function () {
      const that = this
      this.$http.get('categories').then(
        function (res) {
          if (res.data.meta.status !== 200) {
            that.$message.error('获取商品列表失败')
          }
          that.cateList = res.data.data
        })
    },
    // 设置只能选中第三级菜单
    handleChange: function () {
      this.getCateParams()
    },
    handleTabClick: function () {
      this.getCateParams()
    },
    // 获取参数列表
    getCateParams: function () {
      if (this.selectCate.length !== 3) {
        this.selectCate = []
        this.onlyTableData = []
        this.manyTableData = []
      }
      const that = this
      this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      }).then(
        function (res) {
          if (res.data.meta.status !== 200) {
            that.$message.error('获取商品列表失败')
          }
          res.data.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            // 展开行内添加参数表单
            item.inputVisible = false
            item.inputValue = ''
          })
          if (that.activeName === 'many') {
            that.manyTableData = res.data.data
          } else {
            that.onlyTableData = res.data.data
          }
        })
    },
    addDialogClose: function () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮添加参数
    addParmas: function () {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        const that = this
        this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        }).then(
          function (res) {
            console.log(res)
            if (res.data.meta.status !== 201) {
              that.$message.error('添加商品参数失败')
            }
            that.$message.success('添加商品参数成功')
            that.getCateParams()
            that.addDialogVisible = false
          })
      })
    },
    // 显示编辑参数对话框
    editDialog: function (id) {
      const that = this
      this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: {
          attr_sel: this.activeName
        }
      }).then(
        function (res) {
          if (res.data.meta.status !== 200) {
            that.$message.error('获取商品列表失败')
          }
          that.editForm = res.data.data
          console.log(res.data.data)
        })
      this.editDialogVisible = true
    },
    editDialogClose: function () {
      this.$refs.editFormRef.resetFields()
    },
    // 确定修改参数
    editParmas: function () {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return
        const that = this
        this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }).then(
          function (res) {
            if (res.data.meta.status !== 200) {
              that.$message.error('修改商品参数失败')
            }
            console.log(res.data.data)
          })
        that.$message.success('修改商品参数成功')
        this.getCateParams()
        this.editDialogVisible = false
      })
    },
    // 删除参数
    deleteParams: function (id) {
      const that = this
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`categories/${this.cateId}/attributes/${id}`).then(
          function (res) {
            if (res.data.meta.status !== 200) {
              that.$message.error('删除商品参数失败')
            }
            that.getCateParams()
          })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 输入框失去焦点或者回车键按下触发
    handleInputConfirm: function (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
      }
      // 不为空后续操作
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.changeParams(row)
    },
    // 编辑提交参数
    changeParams: function (row) {
      const that = this
      this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      }
      ).then(
        function (res) {
          if (res.data.meta.status !== 200) {
            that.$message.error('修改参数失败')
          }
          that.$message.success('修改参数成功')
        })
    },
    showInput: function (scope) {
      scope.inputVisible = true
    },
    // 删除标签
    deleteTag: function (i, row) {
      row.attr_vals.splice(i, 1)
      this.changeParams(row)
    }
  },
  computed: {
    isBtndisabled () {
      if (this.selectCate.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectCate.length !== 3) {
        return null
      }
      return this.selectCate[2]
    },
    // 添加参数对话框的标题
    Dialogtext () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 10px;
  line-height: 20px;
}
.rowclass {
  text-align: left;
  margin-top: 10px;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>
